package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    // 查询今日佳人
    public ResponseEntity findTodayBest() {
        //  1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询缘分值最高用户
        RecommendUser recommendUser = recommendUserService.findTodayBest(toUserId);
        // 空值处理
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(90, 99));
            recommendUser.setUserId(1L);
            recommendUser.setToUserId(toUserId);
        }
        // 3.封装vo
        // 3-1查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
        // 3-2 创建vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());

        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 查询推荐用户列表
    public ResponseEntity findRecommendUserVoByPage(Integer pageNum, Integer pageSize) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.分页查询推荐用户
        PageBeanVo pageBeanVo = recommendUserService.findRecommedUserByPage(toUserId, pageNum, pageSize);
        // 3.封装vo
        // 3-1 声明voList
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3-2 获取recommendUserList
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3-3 被遍历recommendUserList
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 查询推荐用户的（佳人）userInfo
                UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo); // 用户信息
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值
                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将voList设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 佳人详情
    public ResponseEntity findPersonalInfo(Long jiarenId) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询二人的缘分值
        RecommendUser recommendUser = recommendUserService.findByJiarenIdAndToUserId(jiarenId, toUserId);
        // 空值处理 附近的人要用、我的动态也要用
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(60, 90));
        }
        // 3.查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(jiarenId);
        // 4.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue()); // 设置缘分值

        // 5.返回vo
        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private VisitorService visitorService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 查询历史访客
    public ResponseEntity visitors() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.获取redis中上次登录时间 
        String userLoginTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 3.判断
        List<Visitor> visitorList;
        if (StrUtil.isNotEmpty(userLoginTime)) { // 有
            visitorList = visitorService.findVisitorHead5(userId, Long.valueOf(userLoginTime));
        } else { // 没有
            visitorList = visitorService.findVisitorHead5(userId, System.currentTimeMillis());
        }
        // 4.封装vo
        // 4-1 声明voList
        List<VisitorVo> voList = new ArrayList<>();
        // 4-2 遍历 visitorList
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());
                // 创建vo
                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo); // 用户信息
                vo.setFateValue(visitor.getScore().longValue()); // 你俩的缘分值
                // 添加到集合
                voList.add(vo);
            }
        }
        // 5.记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 6.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserLocationService userLocationService;

    // 调用manager
    public void saveLocation(Double latitude, Double longitude, String addrStr) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存
        userLocationService.saveLocation(latitude, longitude, addrStr, userId);
    }

    // 搜附近
    public ResponseEntity searchNearUser(String gender, Long distance) {
        //  1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);
        // 3.遍历
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {
                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(nearUserId);

                // 排除性别
                if (!StrUtil.equals(userInfo.getGender(), gender)) {
                    continue;
                }

                // 封装vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                // 添加集合
                voList.add(vo);
            }
        }

        // 4.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private QuestionService questionService;

    // 查看对方的陌生人问题
    public ResponseEntity strangerQuestions(Long jiarenId) {
        // 1.查询佳人的陌生人问题
        Question question = questionService.findByUserId(jiarenId);
        // 2.默认值处理
        if (question == null) {
            question = new Question();
        }
        // 3.返回问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
}
